<?php
/**
 * Create by PhpStorm
 * User: lijia
 * Data: 2020/8/10
 * Time: 10:52
 */

namespace app\api\business;


use app\admin\model\Config as ConfigModel;
use app\api\controller\UserCommon;
use app\api\model\Orders;
use think\Exception;
use think\facade\Db;
use think\facade\Request;

class OrdersBus extends UserCommon
{
    public $model;
    public $url;

    public function __construct()
    {
        parent::__construct();
        $this->url = Request::scheme() . '://' . Request::host();
        $this->model = new Orders();
    }

    /**
     * 下单
     * @param $param
     * @return int|string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addOrder($param)
    {
        $address = Db::name('address')->where('id', $param['address_id'])->find();
        if (!$address) {
            throw new Exception('无效的收货地址');
        }
        $ids = $param['ids'];
        $carData = Db::name('shop_car')->alias('a')
            ->join('goods b', 'b.id = a.goods_id')
            ->whereIn('a.id', $ids)
            ->field('a.goods_id,b.deposit_price,a.share_num')
            ->select()->toArray();
        if (empty($carData)) {
            throw new Exception('无效的购物车信息');
        }
        $total_price = 0;
        foreach ($carData as $k => $v) {
            $total_price += $v['deposit_price'] * $v['share_num'];
        }
        $orderData = [
            'order_sn' => date('YmdHis') . random_int(1000000, 9999999),
            'user_id' => $this->user_id,
            'total_price' => $total_price,
            'order_address' => $address['address'],
            'order_name' => $address['name'],
            'order_mobile' => $address['mobile'],
            'create_time' => date('Y-m-d H:i:s')
        ];
        if (isset($param['remarks'])){
            $orderData['remarks'] = $param['remarks'];
        }
        // 插入订单数据
        $orders_id = Db::name('orders')->insertGetId($orderData);
        // 插入订单商品信息
        $goodsData = [];
        foreach ($carData as $k => $v) {
            $goodsData[$k]['orders_id'] = $orders_id;
            $goodsData[$k]['goods_id'] = $v['goods_id'];
            $goodsData[$k]['deposit_price'] = $v['deposit_price'];
            $goodsData[$k]['num'] = $v['share_num'];
            $goods = Db::name('goods')->where('id', $v['goods_id'])->field('id,title,stock')->find();
            if ($goods['stock'] < $v['share_num']) {
                throw new Exception($goods['title'] . ' 库存不足');
            }
            // 减库存
            Db::name('goods')->where('id', $v['goods_id'])->dec('stock', $v['share_num'])->update();
        }
        Db::name('orders_goods')->insertAll($goodsData);
        // 删除购物车信息
        Db::name('shop_car')->whereIn('id', $ids)->delete();
        return $orders_id;
    }


    /**
     * 创建充值订单
     * @param $param
     * @return int|string
     */
    public function recharge($param)
    {
        $param['user_id'] = $this->user_id;
        $param['status'] = 0;
        $param['create_time'] = toDate(time());
        return Db::name('recharge')->insertGetId($param);
    }


    /**
     * 详情
     * @param $id
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info($id)
    {
        $order = Db::name('orders')
            ->where('id', $id)
            ->field('id,order_sn,total_price,status,order_address,order_address,order_name,order_mobile,pay_type,create_time,receipt_time,remarks,comment')
            ->find();
        if (!$order) {
            return [];
        }
        $goods = Db::name('orders_goods')->alias('a')
            ->join('goods b', 'b.id = a.goods_id', 'left')
            ->where('a.orders_id', $order['id'])
            ->field('a.goods_id,a.num,a.deposit_price,b.deduction_price,b.origin_price,b.present_price,b.title,b.cover,b.store_name,b.store_mobile,b.store_address')
            ->select()->toArray();
        foreach ($goods as $key => $val) {
            $goods[$key]['cover'] = $this->url . $val['cover'];
        }
        $order['goods'] = $goods;
        return $order;
    }

    /**
     * 核销
     */
    public function receipt($id)
    {
        $status = $this->model->where('id', $id)->value('status');
        if ($status != 2) {
            throw new Exception('该订单还不能核销');
        }
        return $this->model->where('id',$id)->save(['status' => 3]);
    }


    public function getList($status)
    {
        $where = [
            'user_id' => $this->user_id
        ];
        if ($status != 0) {
            if ($status == 2){
                $orders = Db::name('orders')
                    ->where('status','in','2,3')
                    ->where('user_id',$this->user_id)
                    ->order('id', 'desc')
                    ->field('id,order_sn,total_price,status,create_time,receipt_time')
                    ->select()->toArray();
            }else{
                $where['status'] = $status;
                $orders = Db::name('orders')
                    ->where($where)
                    ->order('id', 'desc')
                    ->field('id,order_sn,total_price,status,create_time,receipt_time')
                    ->select()->toArray();
            }
            foreach ($orders as $k => $v) {
                $goods = Db::name('orders_goods')->alias('a')
                    ->join('goods b', 'b.id = a.goods_id', 'left')
                    ->where('a.orders_id', $v['id'])
                    ->field('a.goods_id,a.num,a.deposit_price,b.deduction_price,b.title,b.cover,b.store_name')
                    ->select()->toArray();
                $total = 0;
                foreach ($goods as $key => $val) {
                    $goods[$key]['cover'] = $this->url . $val['cover'];
                    $total += $val['num'];
                }
                $orders[$k]['goods'] = $goods;
                $orders[$k]['order_goods_total'] = $total;
            }
            return $orders;
        }else{
            $orders = Db::name('orders')
                ->where($where)
                ->order('id', 'desc')
                ->field('id,order_sn,total_price,status,create_time,receipt_time')
                ->select()->toArray();
            foreach ($orders as $k => $v) {
                $goods = Db::name('orders_goods')->alias('a')
                    ->join('goods b', 'b.id = a.goods_id', 'left')
                    ->where('a.orders_id', $v['id'])
                    ->field('a.goods_id,a.num,a.deposit_price,b.deduction_price,b.title,b.cover,b.store_name')
                    ->select()->toArray();
                $total = 0;
                foreach ($goods as $key => $val) {
                    $goods[$key]['cover'] = $this->url . $val['cover'];
                    $total += $val['num'];
                }
                $orders[$k]['goods'] = $goods;
                $orders[$k]['order_goods_total'] = $total;
            }
            return $orders;
        }
    }


    public function comment($id,$comment,$comment_content)
    {
        $status = $this->model->where('id', $id)->value('status');
        if ($status != 4) {
            throw new Exception('该订单还不能评价');
        }
        return $this->model->where('id',$id)->save(['comment' => $comment,'comment_content' => $comment_content,'status' => 5]);
    }


    public function delete($id)
    {
        $order = $this->model->find($id);
        if ($order->status != 1) {
            throw new Exception('该订单不能取消', 0);
        }
        Db::startTrans();
        try {
            $goods = Db::name('orders_goods')->alias('a')
                ->join('goods b', 'b.id =  a.goods_id')
                ->where('a.orders_id', $id)
                ->field('a.goods_id,a.num,b.title,b.stock')
                ->select()->toArray();
            foreach ($goods as $k => $v) {
                // 返回库存
                Db::name('goods')->where('id', $v['goods_id'])->inc('stock', $v['num'])->update();
            }
            Db::name('orders_goods')->where('orders_id', $id)->delete();
            $this->model->where('id', $id)->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }


    /**
     * 余额支付商品订单
     */
    public function balancePay($id)
    {
        $order = $this->model->find($id);
        if ($order->status != 1) {
            throw new Exception('该订单不是未支付的订单', 0);
        }
        Db::startTrans();
        try {
            $money = Db::name('user')->where('user_id', $this->user_id)->value('money');
            if ($money <= $order->total_price) {
                throw new Exception('您的余额不足', 0);
            }
            $data = [
                'status' => 2,
                'pay_type' => 3,
                'pay_time' => toDate(time())
            ];
            $this->model->where('id', $id)->save($data);
            $moneyLog = [
                'user_id' => $order['user_id'],
                'money' => $order['total_price'],
                'type' => 1,
                'status' => 1,
                'create_time' => toDate(time())
            ];
            Db::name('money_log')->insert($moneyLog);
            Db::name('user')->where('user_id', $this->user_id)->dec('money',$order->total_price)->update();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage(), 0);
        }
    }


}